import { defineConfig, loadEnv, ConfigEnv, UserConfig } from "vite";
import { resolve } from "path";
import { visualizer } from 'rollup-plugin-visualizer'
import { wrapperEnv } from "./build/getEnv";
import { createVitePlugins } from "./build/plugins";
import compression from 'vite-plugin-compression';
import pkg from "./package.json";
import dayjs from "dayjs";
const fileVersion = Math.round(Math.random() * new Date().getTime());
const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
};

// @see: https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src"),
        "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js"
      }
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@/styles/var.scss";`
        }
      }
    },
    server: {
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      cors: true,
      hmr: true
      , //热更新
      // Load proxy configuration from .env.development
      // proxy: createProxy(viteEnv.VITE_PROXY)
      proxy: {
        '/api': {
          target: 'http://sscn.tianxuan.work',// 代理的目标地址
          changeOrigin: false,// 开发模式，默认的origin是真实的 origin:localhost:3000 代理服务会把origin修改为目标地址
          ws: true,// 是否代理websockets
          secure: true,// 是否https接口
          rewrite: path => {//路径重写，本项目不需要重写
            return path.replace(new RegExp(`^/api`), "")
          }
        }
      }
    },
    plugins: [
      createVitePlugins(viteEnv),
      // visualizer({
      //   emitFile: false,
      //   filename: 'stats.html',
      //   open: true,
      //   sourcemap: true
      // })

      compression({
        verbose: true,
        disable: false,
        threshold: 30240, // 压缩阈值，小于这个值的文件将不会被压缩（单位为字节）这里就是大于 80kb 压缩
        algorithm: 'gzip', // 压缩算法
        ext: '.gz', // 压缩文件后缀名
      })
 
    ],
    esbuild: {
      pure: viteEnv.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : []
    },
    build: {
      outDir: viteEnv.VITE_OUT_DIR,
      minify: "esbuild",
      // minify: false,
      // esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
      // minify: "terser",
      // terserOptions: {
      // 	compress: {
      // 		drop_console: viteEnv.VITE_DROP_CONSOLE,
      // 		drop_debugger: true
      // 	}
      // },
      sourcemap: false,
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {

          // Static resource classification and packaging

          // chunkFileNames: `assets/js/[name]-[hash].js` ,
          chunkFileNames: `assets/js/[name].js`,
          entryFileNames: `assets/js/[name].js`,
          assetFileNames: `assets/[ext]/[name].[ext]`,
          manualChunks(id) {
          //   // if(id.includes('/node_modules/vue')){
          //   //   return "vueModules"
          //   // }
          //   console.log(id)
            if (id.includes('/node_modules/element-plus')) {
              return "elementPlusModules"
            }
            // if (id.includes('/node_modules/pinia')) {
            //   return "piniaModules"
            // }
            // if (id.includes('/node_modules/axios')) {
            //   return "axiosModules"
            // }
            if (id.includes('/node_modules/vxe-table')) {
              return "vxeTableModules"
            }
            // if (id.includes('/node_modules/vue-router')) {
            //   return "vueRouterModules"
            // }
            // if (id.includes('/node_modules/dayjs')) {
            //   return "dayjsModules"
            // }
            if (id.includes('/node_modules/echarts')) {
              return "echartsModules"
            }
            // if (id.includes('/node_modules/sortablejs')) {
            //   return "sortablejsModules"
            // }
            if (id.includes('/node_modules/lodash')) {
              return "lodashModules"
            }
            //87698
            // if (id.includes('/node_modules/prismjs')) {
            //   return "prismjsModules"
            // }
            // if (id.includes('/node_modules/crypto-js')) {
            //   return "cryptoJsModules"
            // }
           

            return undefined;
          }
        }
      }
    }
  };
});
